package com.security.sm2;

import java.math.BigInteger;
import java.security.KeyPair;

import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.util.encoders.Hex;

public class SM2Utils {

    private static String userId = "123456";

    //获取密钥对
    public static S2KeyPair createKey() {
        KeyPair keyPair = GmUtil.generateKeyPair();
        String privateKey = ((BCECPrivateKey) keyPair.getPrivate()).getD().toString(16);
        System.out.println("私钥"+privateKey);
        String publicKey = Hex.toHexString(((BCECPublicKey) keyPair.getPublic()).getQ().getEncoded(true));
        System.out.println("公钥" + publicKey);
        return new S2KeyPair(publicKey, privateKey);
    }
    //签名
    public static String signSm3WithSm2(String msg, String privateKey) {
        BigInteger d = new BigInteger(privateKey, 16);
        BCECPrivateKey bcecPrivateKey = GmUtil.getPrivatekeyFromD(d);
        byte[] sig = GmUtil.signSm3WithSm2(msg.getBytes(), userId.getBytes(), bcecPrivateKey);
        String hexString = Hex.toHexString(sig);
        System.out.println("签名值"+hexString);
        return hexString;
    }
    //验签
    public static boolean verifySm3WithSm2(String msg, String sig, String publicKey) {
        boolean verify = GmUtil.verifySm3WithSm2(msg.getBytes(), userId.getBytes(), sig.getBytes(), publicKey);
        System.out.println("验签结果"+verify);
        return verify;
    }

}

